<template>
  <div style="z-index: 9999">
    <el-dialog title="文件管理"
               v-model="fileDialogVisible"
               width="80%" @close="closeDialog">
      <div class="table-container">

        <div style="width: 100%; text-align: right; padding: 20px 0">
          <el-button :loading="requestStore.isRequestPending" size="small" @click="getList" type="success"
                     style="margin-right: 10px">查询
          </el-button>
          <el-upload style="display: inline" v-if="hasAuth('sysFile:add')" class="upload-demo"
                     ref="fileUpload"
                     action=""
                     :limit="1"
                     :before-upload="beforeFileUpload"
                     :on-exceed="handleFileExceed"
                     :http-request="(file) => handleFileUpload(file)">
            <el-button size="small" type="success">添加文件</el-button>
          </el-upload>
        </div>
        <el-table :data="fileList"
                  style="width: 100%;"
                  :loading="fileListLoading" border>
          <el-table-column label="文件ID" align="center" prop="id" show-overflow-tooltip/>
          <el-table-column label="文件名称" align="center" prop="fileName" show-overflow-tooltip/>
          <el-table-column label="文件大小" align="center" prop="fileSize">
            <template #default="scope">
              {{ formatFileSize(scope.row.fileSize) }}
            </template>
          </el-table-column>
          <el-table-column label="上传者" align="center" prop="uploadUserName"/>
          <el-table-column label="创建时间" align="center" prop="createTime" show-overflow-tooltip/>
          <el-table-column label="更新时间" align="center" prop="updateTime" show-overflow-tooltip/>

          <el-table-column label="操作" align="center" width="300">
            <template #default="scope">
              <el-button size="small" type="success" @click="handlePreviewFile(scope.row, 'newTag')">新窗口预览
              </el-button>
              <el-button :loading="requestStore.isRequestPending" size="small" type="success"
                         @click="handleDownloadFile(scope.row.id)">下载
              </el-button>
              <el-button :loading="requestStore.isRequestPending"
                         v-if="hasAuth('sysFile:deletePersonalById') || hasAuth('sysFile:delete')" size="small"
                         type="danger" @click="handleDeleteFile(scope.row.id)">删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="closeDialog" size="small">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts">
import {useRequestStore} from '@/store';
import {defineComponent, ref, watch} from 'vue';
import SysFileAPI from '@/api/sysFile/index';
import FilePreview from "./filePreviewOnNewTag.vue";
import {hasAuth} from "@/plugins";
import {ElMessageBox} from 'element-plus';
import {ElMessage} from 'element-plus';

export default defineComponent({
  methods: {hasAuth},
  components: {FilePreview},
  name: "FileManager",
  props: {
    fileKeys: {
      default: ""
    },
    updateObject: {
      default: () => ({})
    },
    visible: {
      default: false
    }
  },
  setup(props, {emit}) {
    const previewVisible = ref(false);
    const fileId = ref('');
    const fileName = ref('');
    const fileDialogVisible = ref(false);
    const fileList = ref([]);
    const fileListLoading = ref(false);
    const requestStore = useRequestStore();
    watch(() => props.visible, (val) => {
      fileDialogVisible.value = val;
      if (val) {
        refresh();
      }
    });

    function gotoUser(nickName: string) {
      emit('router-push', {path: '/systemManage/user', query: {nickName: nickName}});
    }

    function formatFileSize(size: number | undefined): string {
      if (!size) {
        return '-';
      }
      size /= 1024;
      if (size < 1000) {
        return size.toFixed(2) + " KB";
      }
      size /= 1024;
      if (size < 1000) {
        return size.toFixed(2) + " MB";
      }
      size /= 1024;
      return (size / 1024).toFixed(2) + " GB";
    }

    function refresh() {
      getList();
    }

    function getList() {
      fileListLoading.value = true;
      let fileIds = props.updateObject[props.fileKeys as keyof typeof props.updateObject] || '';
      if (!fileIds) {
        fileListLoading.value = false;
        fileList.value = [];
        return;
      }
      SysFileAPI.service('getAllByIds', {fileIds: fileIds}).then(response => {
        fileListLoading.value = false;
        fileList.value = response.data;
      });
    }

    function closeDialog() {
      fileDialogVisible.value = false;
      emit('close');
    }

    function beforeFileUpload(file: any): boolean {
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isLt5M) {
        ElMessage.error('上传文件大小不能超过 5MB!');
      }
      return isLt5M;
    }

    function handleFileExceed() {
      ElMessage.error('只能选择一个文件');
    }

    async function handleFileUpload(file: any) {
      let params = new FormData();
      params.append("file", file.file);
      let headers = {
        'Content-Type': 'multipart/form-data; name="file"'
      };
      try {
        const response = await SysFileAPI.service('uploadFile', params, headers);
        let fileId = response.data.id;
        let fileIds: any = props.updateObject[props.fileKeys as keyof typeof props.updateObject] || '';
        if (fileIds) {
          fileIds += "," + fileId;
        } else {
          fileIds = fileId;
        }
        let updateObject = JSON.parse(JSON.stringify(props.updateObject));
        updateObject[props.fileKeys as keyof typeof props.updateObject] = fileIds;
        const response1 = await new Promise<any>((resolve) => {
          emit("updateFile", 'edit', updateObject, resolve);
        });
        if (response1) {
          ElMessage({
            message: response1.message,
            type: response1.status ? 'success' : 'error'
          });
          if (response1.status) {
            props.updateObject[props.fileKeys as keyof typeof props.updateObject] = fileIds as any;
            getList();
            (this.$refs.fileUpload as any).clearFiles();
          }
        }
      } catch (error) {
        console.error(error);
      }
    }

    async function handleDownloadFile(id: number) {
      try {
        const response = await SysFileAPI.download("downloadPersonalFile", {fileId: id});
        if (response && response.message) {
          ElMessage({
            message: response.message,
            type: response.status ? 'success' : 'error'
          })
        }
      } catch (error) {
        console.error(error);
      }
    }

    async function handleDeleteFile(id: number) {
      try {
        ElMessageBox.confirm(
            '是否要删除该文件？',
            '提示',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }
        ).then(async () => {
          fileListLoading.value = true;
          const response = await SysFileAPI.service('deletePersonalById', {id: id});
          if (response && response.message) {
            ElMessage({
              message: response.message,
              type: response.status ? 'success' : 'error'
            })
            if (!response.status) {
              return;
            }
          }
          let fileIds = props.updateObject[props.fileKeys as keyof typeof props.updateObject] || '';
          let fileIdsArr = fileIds.split(",");
          let deleteIndex = -1;
          for (let i = 0; i < fileIdsArr.length; i++) {
            if (fileIdsArr[i] == id) {
              deleteIndex = i;
              break;
            }
          }
          if (deleteIndex >= 0) {
            fileIdsArr.splice(deleteIndex, 1);
            fileIds = fileIdsArr.join(",");
          }
          let updateObject = JSON.parse(JSON.stringify(props.updateObject));
          updateObject[props.fileKeys as keyof typeof props.updateObject] = fileIds;
          const response1 = await new Promise<any>((resolve) => {
            emit("updateFile", 'edit', updateObject, resolve);
          });
          if (response1) {
            ElMessage({
              message: response1.message,
              type: response1.status ? 'success' : 'error'
            });
            if (response1.status) {
              props.updateObject[props.fileKeys as keyof typeof props.updateObject] = fileIds;
              getList();
            }
          }
          fileListLoading.value = false;
        })


      } catch (error) {
        console.error(error);
      }
    }

    function handlePreviewFile(row: any, openType: string) {
      let name = row.fileName;
      if (openType) {
        window.open(window.origin + '/#/filePreview?fileId=' + row.id + "&fileName=" + encodeURIComponent(name), "_blank");
      } else {
        fileId.value = row.id;
        previewVisible.value = true;
        fileName.value = name;
      }
    }

    return {
      previewVisible,
      fileId,
      fileName,
      fileDialogVisible,
      fileList,
      fileListLoading,
      requestStore,
      gotoUser,
      formatFileSize,
      refresh,
      getList,
      closeDialog,
      beforeFileUpload,
      handleFileExceed,
      handleFileUpload,
      handleDownloadFile,
      handleDeleteFile,
      handlePreviewFile
    };
  }
});
</script>

<style scoped>

</style>



